<template>
  <view class="content" v-if="isShow" @click.stop="isShow = false">
    <canvas
      @click.stop=""
      :style="{ width: canvasW + 'px', height: canvasH + 'px' }"
      canvas-id="my-canvas"
      id="my-canvas"
    ></canvas>
    <view class="save-btn" @tap="saveImage">保存图片</view>
  </view>
</template>

<script lang="ts" setup>
import { ref, getCurrentInstance } from 'vue'

const isShow = ref(false)
const currentInstance = getCurrentInstance()
const ctx = ref()
const canvasW = ref(750)
const canvasH = ref(1334)
const headerImg = 'https://img.yzcdn.cn/vant/cat.jpeg'
// 展示画布
const showCanvas = () => {
  isShow.value = true
  initCanvas()
}

// 初始化画布
const initCanvas = async () => {
  // uni.showLoading({ mask: true, title: '加载中' })
  ctx.value = uni.createCanvasContext('my-canvas', currentInstance)
  canvasW.value = uni.upx2px(550)
  canvasH.value = uni.upx2px(780)
  ctx.value.setFillStyle('rgba(255, 255, 255, 0)')
  // 设置画布大小
  ctx.value.fillRect(0, 0, canvasW.value, canvasH.value)
  // 绘制圆角背景
  drawRoundRect(ctx.value, 0, 0, canvasW.value, canvasH.value, uni.upx2px(18), '#FFFFFF')
  //获取标题图片
  let Img: any = await getImageInfo(headerImg)
  let hW = uni.upx2px(500)
  let hH = uni.upx2px(320)

  ctx.value.drawImage(Img.path, (canvasW.value - hW) / 2, (canvasW.value - hW) / 2, hW, hH)
  ctx.value.draw()
}

//获取图片
const getImageInfo = (imgSrc: any) => {
  return new Promise((resolve, reject) => {
    uni.getImageInfo({
      src: imgSrc,
      success: (image) => {
        resolve(image)
        console.log('获取图片成功', image)
      },
      fail: (err) => {
        reject(err)
        console.log('获取图片失败', err)
      },
    })
  })
}
// 绘制圆角
const drawRoundRect = (
  ctx: any,
  x: number,
  y: number,
  width: number,
  height: number,
  radius: number,
  color: string,
) => {
  ctx.save()
  ctx.beginPath()
  ctx.setFillStyle(color)
  ctx.setStrokeStyle(color)
  ctx.setLineJoin('round') //交点设置成圆角
  ctx.setLineWidth(radius)
  ctx.strokeRect(x + radius / 2, y + radius / 2, width - radius, height - radius)
  ctx.fillRect(x + radius, y + radius, width - radius * 2, height - radius * 2)
  ctx.stroke()
  ctx.closePath()
}

//保存图片到相册
const saveImage = () => {
  //判断用户授权
  uni.getSetting({
    success(res) {
      console.log('获取用户权限', res.authSetting)
      if (Object.keys(res.authSetting).length > 0) {
        //判断是否有相册权限
        if (res.authSetting['scope.writePhotosAlbum'] == undefined) {
          //打开设置权限
          uni.openSetting({
            success(res) {
              console.log('设置权限', res.authSetting)
            },
          })
        } else {
          if (!res.authSetting['scope.writePhotosAlbum']) {
            //打开设置权限
            uni.openSetting({
              success(res) {
                console.log('设置权限', res.authSetting)
              },
            })
          }
        }
      } else {
        return
      }
    },
  })
  uni.canvasToTempFilePath(
    {
      canvasId: 'my-canvas',
      quality: 1,
      complete: (res) => {
        console.log('保存到相册', res)
        uni.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success(res) {
            uni.showToast({
              title: '已保存到相册',
              icon: 'success',
              duration: 2000,
            })
            setTimeout(() => {
              isShow.value = false
            }, 2000)
          },
        })
      },
    },
    this,
  )
}

// 暴露出去的函数

defineExpose({
  showCanvas,
})
</script>

<style scoped lang="scss">
.content {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.4);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  .save-btn {
    margin-top: 35rpx;
    color: #ffffff;
    background: linear-gradient(to right, #fe726b, #fe956b);
    padding: 15rpx 40rpx;
    border-radius: 50rpx;
  }
}
</style>
